<template>
  <div class="main flex width-all">
    <!------------------------------------------ 树 ------------------------------------------------------->

    <div class="tree-view pd10 bg-white mgr20 flex-column">
      <el-input style="width: 240px" v-model="state.customerKeyword" class="mgb10 width-all search" clearable placeholder="客户名或拼音首字母" @keyup.enter="getTreeData">
        <template #append>
          <el-button :icon="Search" @click="filterCustomer" />
        </template>
      </el-input>
      <div class="flex1" style="overflow: auto">
        <TreeVue
          ref="treeEl"
          label="customerName"
          :list="state.treeList"
          node-key="customerName"
          :current-node-key="state.currentNodeKey"
          :expand-on-click-node="false"
          @node-click="onTreeNodeClick"
        />
      </div>
    </div>

    <!------------------------------------------ 表格 ------------------------------------------------------->

    <div class="pd10 bg-white flex1" style="width: calc(100% - 300px)">
      <TabBar v-model="state.formData.faultStatus" class="mgb10" :list="tabBarList" @query="reflesh" />

      <VxeTableVue
        class="width-all"
        ref="tableEl"
        :queryFormData="state.formData"
        :column-config="columnConfig"
        data-list-api="/fault/page"
        :action-column-width="100"
        :show-top-add-btn="false"
        :show-top-del-btn="false"
        :show-del-btn="false"
        :on-mounted-query="false"
        :extra-sub-height="30"
        :fn-object="mapObject"
      >
        <!------------------------------------------ 查询 ------------------------------------------------------->

        <template #queryItem>
          <el-form-item label="故障类型" prop="faultType" class="mgr30">
            <SelectVue v-model="state.formData.faultType" :option-list="faultTypeList" clearable style="width: 160px" />
          </el-form-item>
          <el-form-item label="故障部件" prop="faultDeviceCode" class="mgr30">
            <SelectVue v-model="state.formData.faultDeviceCode" option-api="/fault/listColumnByField" :query-params="{ field: 'fault_device_code' }" clearable style="width: 160px" />
          </el-form-item>
          <el-form-item label="故障发生时间" class="mgr30">
            <DatePickVue v-model:start-time="state.formData.params.faultDiscoveryStartTime" v-model:end-time="state.formData.params.faultDiscoveryEndTime" style="width: 220px" />
          </el-form-item>
        </template>

        <template #moreQuery>
          <el-row>
            <el-col :span="12">
              <el-form-item label="故障编号" prop="faultNo" class="mgr30">
                <el-input v-model="state.formData.faultNo" clearable placeholder="故障编号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="故障描述" prop="faultDesc" class="mgr30">
                <el-input v-model="state.formData.faultDesc" clearable placeholder="故障描述" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="修复人员" prop="faultRepairedBy" class="mgr30">
                <SelectVue v-model="state.formData.faultRepairedBy" value="name" :teleported="false" option-api="/fault/listColumnByField" :query-params="{ field: 'fault_repaired_by' }" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="服务人员" class="mgr30">
                <SelectVue v-model="state.formData.params.userId" :teleported="false" option-api="/auth/role/getUserByRoleName" :query-params="{ roleName: '服务人员' }" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="故障修复时间" class="mgr30">
                <DatePickVue v-model:start-time="state.formData.params.faultRepairedStartTime" v-model:end-time="state.formData.params.faultRepairedEndTime" :teleported="false" style="width: 240px" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="产品型号" prop="productionNumber" class="mgr30">
                <el-input v-model="state.formData.productionNumber" clearable placeholder="产品型号" />
              </el-form-item>
            </el-col>
          </el-row>
        </template>

        <!------------------------------------------ 表格列 ------------------------------------------------------->

        <template #faultType="{ row }: SlotFault">
          <div>{{ faultTypeList?.find(item => item.id === row.faultType)?.name }}</div>
        </template>

        <template #faultStatus="{ row }: SlotFault">
          <!-- <div>{{ tabBarList?.find(item => item.value === row.faultStatus)?.label }}</div> -->
          <el-tag :type="row.faultStatus === '1' ? 'warning' : row.faultStatus === '2' ? 'success' : 'primary'">{{
            row.faultStatus === '1' ? '待修复' : row.faultStatus === '2' ? '已修复' : '待通知'
          }}</el-tag>
        </template>

        <template #faultLocation="{ row }: SlotFault">
          <div>{{ row.faultLineCode + '-' + row.faultStationCode }}</div>
        </template>

        <template #faultPersistTime="{ row }: SlotFault">
          <div>{{ row.faultRepairedTime ? calDuration(row.faultDiscoveryTime, row.faultRepairedTime) : calDuration(row.faultDiscoveryTime, new Date()) }}</div>
        </template>

        <template #userList="{ row }: SlotFault">
          <div>{{ row.userList?.map(item => item.name)?.join(',') }}</div>
        </template>

        <template #extraBtn1="{ row }: SlotFault">
          <el-button link type="primary" @click="checkDetail(row)">详情</el-button>
        </template>
      </VxeTableVue>
    </div>

    <!------------------------------------------ 详情 ------------------------------------------------------->
    <DrawerVue ref="drawerDetailEl" title="详情" :show-footer="false" size="40%">
      <Detail :data="state.currentRow" :fault-type-list="faultTypeList" />
    </DrawerVue>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onActivated, nextTick } from 'vue'
  import { Search } from '@element-plus/icons-vue'
  import TreeVue, { type TreeVueInstance } from '@/components/tree'
  import TabBar from '@/components/tab-bar'
  import DrawerVue, { type DrawerVueInstance } from '@/components/drawer'
  import { VxeTableVue, type VxeTableViewInstance, type IPropsFnObject } from '@/components/table'
  import DatePickVue from '@/components/date-pick'
  import SelectVue from '@/components/select'
  import { columnConfig } from './config'
  import request, { type IPage } from '@/service'
  import type { ICustomerEntity, SlotFault, IFault } from './config'
  import { Ui, calDuration } from '@/utils'
  import Detail from './cpns/drawer-detail.vue'
  import router from '@/router'

  const tableEl = ref<VxeTableViewInstance>()
  const drawerDetailEl = ref<DrawerVueInstance>()
  const treeEl = ref<TreeVueInstance>()

  const state = reactive({
    currentNodeKey: '客户/全部',
    treeList: [{ id: '1', customerName: '客户/全部', children: [] as ICustomerEntity[] }],
    customerKeyword: '',
    formData: {
      customerName: '',
      faultStatus: '',
      faultType: '',
      faultDeviceCode: '',
      faultNo: '',
      faultDesc: '',
      faultRepairedBy: '',
      productionNumber: '',

      params: {
        userId: '',
        faultDiscoveryStartTime: '',
        faultDiscoveryEndTime: '',
        faultRepairedStartTime: '',
        faultRepairedEndTime: ''
      }
    },

    currentRow: {} as IFault
  })

  const faultTypeList = [
    { name: '机械故障', id: '0' },
    { name: '电控故障', id: '1' },
    { name: '软件故障', id: '2' }
  ]

  const tabBarList = [
    { label: '全部', value: '' },
    { label: '待通知', value: '0' },
    { label: '待修复', value: '1' },
    { label: '已修复', value: '2' }
  ]

  let customerList: ICustomerEntity[] = []

  const mapObject: IPropsFnObject = {
    mapColumn(list: typeof columnConfig) {
      if (['', '2'].includes(state.formData.faultStatus)) {
        return list.filter(item => item.field !== 'bizPerson')
      }
      //@ts-ignore
      if (['0', '1'].includes(state.formData.faultStatus)) return list.filter(item => !['faultRepairedTime', 'faultRepairedBy'].includes(item.field))

      return list
    }
  }

  /**----------------------------methods----------------------------------------------------------------------- */

  const checkDetail = (row: IFault) => {
    state.currentRow = row
    drawerDetailEl.value?.handleOpen()
  }

  interface ITreeData {
    node: ICustomerEntity
  }
  const onTreeNodeClick = ({ node }: ITreeData) => {
    state.formData.customerName = node.customerName === '客户/全部' ? '' : node.customerName
    state.currentNodeKey = node.customerName
    reflesh()
  }

  const filterCustomer = () => {
    if (!state.customerKeyword) return (state.treeList[0].children = customerList)
    state.treeList[0].children = customerList.filter(item => item.customerNamePy.includes(state.customerKeyword) || item.customerName.includes(state.customerKeyword))
  }

  const getTreeData = () => {
    request.get<IPage<ICustomerEntity>>('/customer/page', { current: 1, size: 9999, customerStatus: '1' }).then(res => {
      if (res.code !== 0) return Ui.useMessage('error', res.msg)
      customerList = res.data.records
      state.treeList[0].children = customerList
      nextTick(() => {
        treeEl.value?.setCurrentKey(state.currentNodeKey)
      })
    })
  }

  const reflesh = () => {
    tableEl.value?.query()
  }

  /**----------------------------lifecycle----------------------------------------------------------------------- */
  onActivated(() => {
    const { faultDiscoveryStartTime, faultDiscoveryEndTime, customerName, faultDeviceCode, productionNumber } = router.currentRoute.value.query
    state.formData.params.faultDiscoveryStartTime = faultDiscoveryStartTime as string
    state.formData.params.faultDiscoveryEndTime = faultDiscoveryEndTime as string
    state.formData.customerName = state.formData.customerName ? state.formData.customerName : (customerName as string)
    state.formData.faultDeviceCode = faultDeviceCode as string
    state.formData.productionNumber = productionNumber as string
    state.currentNodeKey = (state.formData.customerName ?? '客户/全部') as string

    reflesh()
  })

  getTreeData()
</script>

<style scoped lang="less">
  .main {
    padding: 0;
    background: #f2f6fc;
    .bg-white {
      background: #fff;
    }
  }
</style>
